CC=gcc
DEFINES=
#-DTOWERHACK_DEBUG=1 -DTOWERHACK_DEBUG_ARENA=0 -DTOWERHACK_DEBUG_NETWORK=0 -DTOWERHACK_DEBUG_LOGIC=0
INCLUDES=-I$(SRCDIR)
CFLAGS=-g --std=gnu99 -Wall -Werror -fgnu89-inline 
DEPCOMP=gcc -MM $(CFLAGS) $(INCLUDES)
LD=gcc
LDFLAGS=$(shell allegro-config --libs) -lbsd-compat -pthread
CHECK_LDFLAGS=-lcheck
RM=rm -f
MKDIR=mkdir -p

SRCDIR=src
OBJDIR=obj
DEPDIR=deps
BINDIR=bin

FINDCMD=find $(SRCDIR) -name EXCLUDEDIR -prune -o -name "*.c" -print
CLIENT_SRCS=$(shell $(FINDCMD:EXCLUDEDIR=server))
SERVER_SRCS=$(shell $(FINDCMD:EXCLUDEDIR=client))
CLIENT_OBJS=$(subst $(SRCDIR)/,$(OBJDIR)/,$(CLIENT_SRCS:%.c=%.o))
SERVER_OBJS=$(subst $(SRCDIR)/,$(OBJDIR)/,$(SERVER_SRCS:%.c=%.o))
ALL_OBJS=$(CLIENT_OBJS) $(SERVER_OBJS)
CLIENT_BIN=$(BINDIR)/towerhack
SERVER_BIN=$(BINDIR)/towerhackd


.PHONY: all run_server run_client run server client towerhackd towerhack check doc clean

all: server client

run-server: server
	exec $(SERVER_BIN)

run-client run: client
	exec $(CLIENT_BIN) -r -c localhost ADmiral

run-both: client
	exec $(SERVER_BIN) & exec $(CLIENT_BIN) -r -c localhost ADmiral


server towerhackd: $(SERVER_BIN)

client towerhack: $(CLIENT_BIN)

$(SERVER_BIN): $(SERVER_OBJS)
	$(MKDIR) `dirname $(SERVER_BIN)`
	$(LD) $(LDFLAGS) $(SERVER_OBJS) -o $(SERVER_BIN)

$(CLIENT_BIN): $(CLIENT_OBJS)
	$(MKDIR) `dirname $(CLIENT_BIN)`
	$(LD) $(LDFLAGS) $(CLIENT_OBJS) -o $(CLIENT_BIN)


$(OBJDIR)/server/%.o: $(SRCDIR)/server/%.c
	$(MKDIR) `dirname $@` `dirname $(DEPDIR)/server/$*.d`
	$(CC) $(CFLAGS) $(DEFINES) $(INCLUDES) -DTARGET_SERVER=1 -c $< -o $@
	printf "%s/%s" `dirname $@` "`$(DEPCOMP) $<`" > $(DEPDIR)/$*.d

$(OBJDIR)/client/%.o: $(SRCDIR)/client/%.c
	$(MKDIR) `dirname $@` `dirname $(DEPDIR)/client/$*.d`
	$(CC) $(CFLAGS) $(DEFINES) $(INCLUDES) -DTARGET_CLIENT=1 -c $< -o $@
	printf "%s/%s" `dirname $@` "`$(DEPCOMP) $<`" > $(DEPDIR)/$*.d

$(OBJDIR)/%.o: $(SRCDIR)/%.c
	$(MKDIR) `dirname $@` `dirname $(DEPDIR)/$*.d`
	$(CC) $(CFLAGS) $(DEFINES) $(INCLUDES) -c $< -o $@
	printf "%s/%s" `dirname $@` "`$(DEPCOMP) $<`" > $(DEPDIR)/$*.d

-include $(ALL_OBJS:$(OBJDIR)/%.o=$(DEPDIR)/%.d)

CHECK_FILES=tests/* src/generator/graph.c src/util/mt.c src/util/trimatrix.c 

check: $(BINDIR)/check
	$(BINDIR)/check

$(BINDIR)/check: $(CHECK_FILES)
	$(CC) $(CFLAGS) $(INCLUDES) $(LDFLAGS) $(CHECK_LDFLAGS) -o $@ $^

doc:
	doxygen Doxyfile

clean:
	$(RM) -r $(BINDIR) $(OBJDIR) $(DEPDIR)
